<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>新建</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
	<h1>新建Customer</h1>

	<br />
	<form id="form" th:action="@{/create}" method="post">
		客户名称：<input type="text" name="name" value="" /> <br /> <a href="javascript:void(0);" id="submit">提交</a>
	</form>
	<script>
		/*<![CDATA[*/
		$(function() {
			$("#submit").click(function() {
				var data = $("#form").serializeArray();
				data = convertToJson(data);
				$.ajax({
					type : "POST",
					url : "/create",
					data : JSON.stringify(data),
					dataType : 'json',
					contentType : 'application/json;charset=UTF-8', //contentType很重要  
					success : function(data) {
						console.log("response", data)
					}
				});
			});
		});

		/**
		 * 将表单对象转为json对象
		 * @param formValues
		 * @returns
		 */
		function convertToJson(formValues) {
			var result = {};
			for (var formValue, j = 0; j < formValues.length; j++) {
				formValue = formValues[j];
				var name = formValue.name;
				var value = formValue.value;
				if (name.indexOf('.') < 0) {
					if (result[name]) {
						result[name] = result[name] + "," + value;
					} else {
						result[name] = value;
					}
					continue;
				} else {
					var simpleNames = name.split('.');
					// 构建命名空间
					var obj = result;
					for (var i = 0; i < simpleNames.length - 1; i++) {
						var simpleName = simpleNames[i];
						if (simpleName.indexOf('[') < 0) {
							if (obj[simpleName] == null) {
								obj[simpleName] = {};
							}
							obj = obj[simpleName];
						} else { // 数组
							// 分隔
							var arrNames = simpleName.split('[');
							var arrName = arrNames[0];
							var arrIndex = parseInt(arrNames[1]);
							if (obj[arrName] == null) {
								obj[arrName] = []; // new Array();
							}
							obj = obj[arrName];
							multiChooseArray = result[arrName];
							if (obj[arrIndex] == null) {
								obj[arrIndex] = {}; // new Object();
							}
							obj = obj[arrIndex];
						}
					}

					if (obj[simpleNames[simpleNames.length - 1]]) {
						var temp = obj[simpleNames[simpleNames.length - 1]];
						obj[simpleNames[simpleNames.length - 1]] = temp;
					} else {
						obj[simpleNames[simpleNames.length - 1]] = value;
					}

				}
			}
			return result;
		}
		/*]]>*/
	</script>
</body>
</html>